package org.jeecg.modules.activities.controller;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.activities.entity.FhActive;
import org.jeecg.modules.activities.entity.FhChallenroll;
import org.jeecg.modules.activities.entity.FhMytrip;
import org.jeecg.modules.activities.service.IFhChallenrollService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 挑战报名
 * @Author: jeecg-boot
 * @Date:   2024-07-16
 * @Version: V1.0
 */
@Api(tags="305挑战报名")
@RestController
@RequestMapping("/activities/fhChallenroll")
@Slf4j
public class FhChallenrollController extends JeecgController<FhChallenroll, IFhChallenrollService> {
	@Autowired
	private IFhChallenrollService fhChallenrollService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;


	 /**
	  * 分页列表查询
	  *
	  * @param fhChallenroll
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "挑战报名-分页列表查询")
	 @ApiOperation(value="挑战报名-分页列表查询", notes="挑战报名-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<FhChallenroll>> queryPageList(FhChallenroll fhChallenroll,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {

		 QueryWrapper<FhChallenroll> queryWrapper = QueryGenerator.initQueryWrapper(fhChallenroll, req.getParameterMap());
		 Page<FhChallenroll> page = new Page<FhChallenroll>(pageNo, pageSize);
		 IPage<FhChallenroll> pageList = fhChallenrollService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }



	 /**
	 * 分页列表查询
	 *
	 * @param fhChallenroll
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "挑战报名-分页列表查询")
	@ApiOperation(value="挑战报名-神秘暗号过滤已完成激活的列表查询", notes="挑战报名-神秘暗号过滤已完成激活的列表查询")
	@GetMapping(value = "/listjh")
	public Result<IPage<FhChallenroll>> queryPagejhList(FhChallenroll fhChallenroll,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String realName = fhChallenroll.getRealname();
		if(oConvertUtils.isNotEmpty(realName)){
			fhChallenroll.setRealname(null);
		}
		QueryWrapper<FhChallenroll> queryWrapper = QueryGenerator.initQueryWrapper(fhChallenroll, req.getParameterMap());
		// 直接获取当前用户
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if (oConvertUtils.isEmpty(loginUser)) {
			 return Result.error("请登录系统！");
		 }
		IPage<FhChallenroll> pageList = new Page<FhChallenroll>();
		Page<FhChallenroll> page = new Page<FhChallenroll>(pageNo, pageSize);
		queryWrapper.and(wrapper -> wrapper
				 .ne("user_id", loginUser.getId())//过滤掉自己
				 .le("bjh",0)//被我激活数<0，就是我没有激活过她，但别人有可能激活过他
		);
		if(oConvertUtils.isNotEmpty(realName)){

			queryWrapper.and(wrapper -> wrapper
					.like("realname",realName)
			);
		}
		List<FhChallenroll> fhChallenrollList = fhChallenrollService.selectjhPage(loginUser.getId(),page, queryWrapper);
		pageList.setRecords(fhChallenrollList);

		return Result.OK(pageList);
	}

	 /**
	  *   检查是否已报名
	  *
	  * @param fhChallenroll
	  * @return
	  */
	 @ApiOperation(value="挑战赛-检查是否已报名", notes="挑战赛-检查是否已报名")
	 //@RequiresPermissions("org.jeecg.modules:fh_challenge:add")
	 @PostMapping(value = "/CheckExists")
	 public Result<String> CheckExists(@RequestBody FhChallenroll fhChallenroll) {
		 if(fhChallenroll==null){
			 return Result.error("没有过滤参数！");
		 }
		 QueryWrapper queryWrapper = new QueryWrapper();
		 queryWrapper.eq("user_id", fhChallenroll.getUserId());
		 queryWrapper.eq("parent_id", fhChallenroll.getParentId());
		 List<FhChallenroll> fhChallenrollList= fhChallenrollService.list(queryWrapper);
		 if(fhChallenrollList!=null && fhChallenrollList.size()>0){
			 return Result.error("用户已报名！");
		 }
		 return Result.OK("用户未报名！");
	 }

	
	/**
	 *   添加
	 *
	 * @param fhChallenroll
	 * @return
	 */
	@AutoLog(value = "挑战报名-添加")
	@ApiOperation(value="挑战报名-添加", notes="挑战报名-添加")
	//@RequiresPermissions("org.jeecg.modules:fh_challenroll:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody FhChallenroll fhChallenroll) {
		if(fhChallenrollService.save(fhChallenroll)) {
			if (fhChallenroll != null && fhChallenroll.getParentId() != null && fhChallenroll.getUserId() != null) {
				//神秘暗号更新照片到头像
				if (fhChallenroll.getParentId().equals("1811748101918572546") &&
						oConvertUtils.isNotEmpty(fhChallenroll.getPicture())) {
					SysUser sysUser = sysUserService.getById(fhChallenroll.getUserId());
					if (sysUser != null) {
						sysUser.setAvatar(fhChallenroll.getPicture());
						sysUserService.updateById(sysUser);
					}
				}
			}
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fhChallenroll
	 * @return
	 */
	@AutoLog(value = "挑战报名-编辑")
	@ApiOperation(value="挑战报名-编辑", notes="挑战报名-编辑")
	//@RequiresPermissions("org.jeecg.modules:fh_challenroll:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody FhChallenroll fhChallenroll) {
		fhChallenrollService.updateById(fhChallenroll);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "挑战报名-通过id删除")
	@ApiOperation(value="挑战报名-通过id删除", notes="挑战报名-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:fh_challenroll:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {

		FhChallenroll fhChallenroll = fhChallenrollService.getById(id);
		if (oConvertUtils.isNotEmpty(fhChallenroll.getPicture())) {
			String[] array = fhChallenroll.getPicture().split(",");
			if (array != null && array.length > 0) {
				for (String img : array) {
					if (oConvertUtils.isNotEmpty(img)) {
						File file = new File(uploadpath + File.separator + img);
						if (file.exists()) {
							// 创建文件根目录
							file.delete();
						}
					}
				}
			}
		}

		fhChallenrollService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "挑战报名-批量删除")
	@ApiOperation(value="挑战报名-批量删除", notes="挑战报名-批量删除")
	//@RequiresPermissions("org.jeecg.modules:fh_challenroll:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {

		if(oConvertUtils.isNotEmpty(ids)&& ids.length()>0) {
			String[] idArray = ids.split(",");
			for(String id:idArray) {
				FhChallenroll fhChallenroll = fhChallenrollService.getById(id);
				if (oConvertUtils.isNotEmpty(fhChallenroll.getPicture())) {
					String[] array = fhChallenroll.getPicture().split(",");
					if (array != null && array.length > 0) {
						for (String img : array) {
							if (oConvertUtils.isNotEmpty(img)) {
								File file = new File(uploadpath + File.separator + img);
								if (file.exists()) {
									// 创建文件根目录
									file.delete();
								}
							}
						}
					}
				}
			}
		}


		this.fhChallenrollService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "挑战报名-通过id查询")
	@ApiOperation(value="挑战报名-通过id查询", notes="挑战报名-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FhChallenroll> queryById(@RequestParam(name="id",required=true) String id) {
		FhChallenroll fhChallenroll = fhChallenrollService.getById(id);
		if(fhChallenroll==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(fhChallenroll);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fhChallenroll
    */
    //@RequiresPermissions("org.jeecg.modules:fh_challenroll:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FhChallenroll fhChallenroll) {
        return super.exportXls(request, fhChallenroll, FhChallenroll.class, "挑战报名");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("fh_challenroll:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FhChallenroll.class);
    }

}
